/*
 * Sender.java
 *
 * Created on 10 de Outubro de 2007, 09:21
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package br.gfca.netsender;

import br.gfca.netsender.exeptions.InternalException;
import br.gfca.netsender.exeptions.UnknownException;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 *
 * @author Gustavo
 */
public class Sender {
    
    /** Creates a new instance of Sender */
    public Sender() {
    }
    
    public static void send( String destinatario, String mensagem ) throws UnknownException, InternalException {

        StringBuilder errorMessage = new StringBuilder();
        
        try {
            Runtime rt = Runtime.getRuntime();
            Process proc = rt.exec("net send /domain:" + destinatario + " \"" + mensagem + "\"" );
            
            InputStream stderr = proc.getErrorStream();
            InputStreamReader isr = new InputStreamReader(stderr);
            BufferedReader br = new BufferedReader(isr);
            String line = null;
            System.out.println("<ERROR>");
            while ( (line = br.readLine()) != null) {
                System.out.println(line);
                errorMessage.append( line + System.getProperty("line.separator") );
            }                
            System.out.println("</ERROR>");
            
            int exitVal = proc.waitFor();
            System.out.println("Process exitValue: " + exitVal);
        }
        catch (Throwable t) {
            t.printStackTrace();
            throw new UnknownException( "Erro desconhecido: " + t.getMessage() );
        }     
        
        if ( errorMessage.length() > 0 ) {
            throw new InternalException( "Erro interno do comando: " + errorMessage.toString().trim() );
        }
    }    
}
